from rest_framework import serializers

from oauth.models import OAuthQQUser, OAuthWeiboUser
from oauth.utils import decode_sign_openid
from django_redis import get_redis_connection

from users.models import User


class OAuthQQUserSerializer(serializers.Serializer):

    access_token = serializers.CharField(label="加密openid")
    mobile = serializers.RegexField(label="手机号",regex=r'^1[3-9]\d{9}$')
    sms_code = serializers.CharField(min_length=6,max_length=6,label="短信")
    password = serializers.CharField(min_length=8, max_length=20, label="密码")

    #1,多字段校验
    def validate(self, attrs):
        #1,校验openid
        openid = decode_sign_openid(attrs["access_token"])
        if not openid:
            raise serializers.ValidationError("openid错误")

        #2,校验短信验证码
        mobile = attrs["mobile"]
        sms_code = attrs["sms_code"]

        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码过期")

        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")

        #3,校验密码
        user = None
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            #判断密码是否正确
            if not user.check_password(attrs["password"]):
                raise serializers.ValidationError("密码错误")

        #4,返回,添加user和opeid
        attrs["openid"] = openid
        attrs["user"] = user
        return attrs

    #2,重写create方法入库数据
    def create(self, validated_data):
        """
        :param validated_data:就是上面校验之后的数据
        :return:
        """
        #1,获取数据
        openid = validated_data["openid"]
        user = validated_data["user"]

        #2,判断是否存在user
        if not user:
            user = User.objects.create_user(
                username=validated_data["mobile"],
                password=validated_data["password"],
                mobile=validated_data["mobile"]
            )

        #3,创建OAuthQQUser对象,绑定美多用户
        OAuthQQUser.objects.create(openid=openid,user=user)

        #4,返回
        return user

class OAuthWeiboUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label="加密access_token")
    mobile = serializers.RegexField(label="手机号",regex=r'^1[3-9]\d{9}$')
    sms_code = serializers.CharField(min_length=6,max_length=6,label="短信验证码")
    password = serializers.CharField(min_length=8, max_length=20, label="密码")

    #1,多字段校验
    def validate(self, attrs):
        #1,校验openid
        openid = decode_sign_openid(attrs["access_token"])
        if not openid:
            raise serializers.ValidationError("access_token错误")
        #2,校验短信验证码
        mobile = attrs["mobile"]
        
        sms_code = attrs["sms_code"]
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码过期")

        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")

        #3,校验密码
        user = None
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            #判断密码是否正确
            if not user.check_password(attrs["password"]):
                raise serializers.ValidationError("密码错误")

        #4,返回,添加user和opeid
        attrs["openid"] = openid
        attrs["user"] = user
        return attrs

    #2,重写create方法入库数据
    def create(self, validated_data):
        #1,获取数据
        openid = validated_data["openid"]
        user = validated_data["user"]

        #2,判断是否存在user
        if not user:
            user = User.objects.create_user(
                username=validated_data["mobile"],
                password=validated_data["password"],
                mobile=validated_data["mobile"]
            )

        #3,创建OAuthQQUser对象,绑定美多用户
        OAuthWeiboUser.objects.create(access_token=openid,user=user)

        #4,返回
        return user